package com.alibaba.service.impl;

import com.alibaba.mapper.ArticleMapper;
import com.alibaba.service.ArticleService;
import com.alibaba.utils.BizException;
import jakarta.annotation.Resource;
import lombok.val;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 *
 * @author ZhouYaDong
 * @date 2025/9/25
 * @description
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final String ARTICLE_VIEW_KEY_PREFIX = "article:view:";

    /**
     * 浏览文章
     * @param articleId 文章ID
     */
    @Override
    public void viewArticle(Long articleId) {
        // 查询数据库是否存在该文章
        val article = articleMapper.selectById(articleId);
        if (article == null) {
           throw new BizException("Article not found");
        }
        String key = ARTICLE_VIEW_KEY_PREFIX + articleId;
        redisTemplate.opsForValue().increment(key, 1); // 每次访问 +1
    }
}
